package DAO;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;

public class RoomDao {
	private Connection conn;
	public RoomDao(Connection conn) {
		this.conn = conn;
	}
	// 通过roomName获得roomId
	public int getIdByName(String roomName) {
		int roomId = 0;
		String query = "SELECT * FROM room WHERE room_name = '" + roomName + "'";
		try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果
            if (resultSet.next()) {
            	roomId = resultSet.getInt("room_id");
            	System.out.println("成功找到room：" + roomName + roomId);
            }
            stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
        return roomId; // 如果是0就说明没有找到，否则是roomId
	}
	// 通过roomId获得roomName
	public String getNameById(int roomId) {
		String roomName = "";
		String query = "SELECT * FROM room WHERE room_id = '" + roomId + "'";
		try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果
            if (resultSet.next()) {
            	roomName = resultSet.getString("room_name");
            	System.out.println("成功找到room：" + roomName + roomId);
            }
            stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
        return roomName; // 如果是0就说明没有找到，否则是roomId
	}
	// 注册一个房间，返回 一个房间id，不允许重名
	public int createRoom(int userId, String roomName) {
	/*	if(getIdByName(roomName) != 0)
			return -1; // 重名，不允许  */
		int roomId = 0;
		String sql = "INSERT INTO room (user_id_1, user_id_2, user_id_3, user_id_4, user_id_5, room_name, user_num) VALUES (?, ?, ?, ?, ?, ?, ?)";
		try {
			PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			stmt.setInt(1, userId);
			for(int i = 2; i <= 5; i++) {
				stmt.setInt(i, -1);
			}
			stmt.setString(6, roomName);
			stmt.setInt(7, 1); // 一开始只有一个人
			// 执行插入操作
			stmt.executeUpdate();
	        // 获取生成的主键 ID
	        ResultSet generatedKeys = stmt.getGeneratedKeys();
	        if (generatedKeys.next()) {
	            roomId = generatedKeys.getInt(1);
	        }
	        stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}
		return roomId;
	}
	// 加入一个房间,user_num++,user_id更新,用于添加两个好友之间的房间
	public int joinNewRoom(int userId, int roomId,int myaccount,int faccount) {
        String query = "SELECT * FROM room WHERE room_id = " + roomId;
        String update1 = "UPDATE room SET user_num = user_num + 1, user_id_";
        String update2 = " = ? , room_account = ?  WHERE room_id = " + roomId;
        int check = 0;
        int userNum = 0;
        int isIn = 0;
        try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果,只有一条，所以用if
            if (resultSet.next()) {
                userNum = resultSet.getInt("user_num");
                System.out.println("User Num: " + userNum);
                // 检查是不是已经在房间里了
                for(int i = 1; i <= userNum; i++) {
                	if(resultSet.getInt("user_id_" + i) == userId)
                		isIn++;
                }
            }
            stmt.close();
            
            // 要是已经五个人，那就加入失败
            if(userNum == 5) {
            	System.out.println("已达最大人数数量，不能再加入");
            	return -2;
            }
            // 要是已经加入该房间，就加入失败
            if(isIn > 0) {
            	System.out.println("已经加入该房间，不能再加入");
            	return -1;
            }
            
            // 建立 PreparedStatement 对象执行插入
            userNum++;
            String update = update1 + userNum + update2;
            String roomaccount = String.valueOf(myaccount)+String.valueOf(faccount);
            System.out.println(update);
            PreparedStatement pstmt = conn.prepareStatement(update);
            pstmt.setInt(1, userId);
            pstmt.setLong(2, Long.parseLong(roomaccount));
            check = pstmt.executeUpdate(); 
            pstmt.close();
        } catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
        if(check > 0) { // 插入行数，检查是否成功
			System.out.println("加入房间成功！");
			return 0;
        } else {
			System.out.println("加入房间失败！");
			return -3; // 未知错误
        }
	}
	
	//通过房间号来加入房间，用于群聊
	public int joinNewRoomByAccount(int userId,int roomAccount) {
		String query = "SELECT * FROM room WHERE room_account = " + roomAccount;
        String update1 = "UPDATE room SET user_num = user_num + 1, user_id_";
        String update2 = " = ?  WHERE room_account = " + roomAccount;
        int check = 0;
        int userNum = 0;
        int isIn = 0;
        try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果,只有一条，所以用if
            if (resultSet.next()) {
                userNum = resultSet.getInt("user_num");
                System.out.println("User Num: " + userNum);
                // 检查是不是已经在房间里了
                for(int i = 1; i <= userNum; i++) {
                	if(resultSet.getInt("user_id_" + i) == userId)
                		isIn++;
                }
            }
            stmt.close();
            
            // 要是已经五个人，那就加入失败
            if(userNum == 5) {
            	System.out.println("已达最大人数数量，不能再加入");
            	return -2;
            }
            // 要是已经加入该房间，就加入失败
            if(isIn > 0) {
            	System.out.println("已经加入该房间，不能再加入");
            	return -1;
            }
            
            // 建立 PreparedStatement 对象执行插入
            userNum++;
            String update = update1 + userNum + update2;
            PreparedStatement pstmt = conn.prepareStatement(update);
            pstmt.setInt(1, userId);
            check = pstmt.executeUpdate(); 
            pstmt.close();
        } catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
        if(check > 0) { // 插入行数，检查是否成功
			System.out.println("加入房间成功！");
			return 0;
        } else {
			System.out.println("加入房间失败！");
			return -3; // 未知错误
        }
	}
	
	// 获得当前房间所有用户
	public  Vector<Integer> getAllUser(int roomId) {
		Vector<Integer> userIds = new Vector<>();
		String query = "SELECT * FROM room WHERE room_id = " + roomId;
	    try {
	        // 创建 Statement 对象执行查询
	        Statement stmt = conn.createStatement();
	        ResultSet resultSet = stmt.executeQuery(query);
	        // 处理查询结果
	        if (resultSet.next()) {
	            for (int i = 1; i <= 5; i++) {
	            	int userId = resultSet.getInt("user_id_" + i);
	            	if (userId == -1)
	            		break;
	            	else 
	            		userIds.add(userId);
	            }
	        }
	        stmt.close();
	    } catch (Exception e) {
			// TODO: handle exception
	        System.out.println(e);
		}
	    return userIds;
	}
	// 退出一个聊天室,因为跟客户端的列表一一对应，所以传index更好操作
	public boolean leaveTheRoom(int userId, int roomId) {
		// 首先根据roomId进行一些查询
		String query = "SELECT * FROM room WHERE room_id = " + roomId;
		int index = -1;
	    try {
	        // 创建 Statement 对象执行查询
	        Statement stmt = conn.createStatement();
	        ResultSet resultSet = stmt.executeQuery(query);
	        // 处理查询结果
	        if (resultSet.next()) {
	        	// 这时房间只剩一个人，再退出，则就把房间注销掉
	        	if(resultSet.getInt("user_num") == 1) {
	        		if(deleteRoom(roomId))
	        			return true;
	        		else
	        			return false;
	        	}
	        	// 否则找到该用户的下标
	            for (int i = 1; i <= 5; i++) {
	            	if (resultSet.getInt("user_id_" + i) == userId) {
	            		index = i;
	            		System.out.println(index);
	            		break;
	            	}
	            }
	        }
	        stmt.close();
	    } catch (Exception e) {
			// TODO: handle exception
	        System.out.println(e);
		}
		
	    // 然后根据index进行一些操作
		int check = 0;
		String update = "UPDATE room SET ";
		for (int i = index; i < 5; i++) {
		    update += "user_id_" + i + " = user_id_" + (i + 1) + ", ";
		}
		update += "user_id_5 = -1, user_num = user_num - 1 WHERE room_id = ?";

		try {
		    PreparedStatement updateStmt = conn.prepareStatement(update);
		    updateStmt.setInt(1, roomId);
		    check = updateStmt.executeUpdate();
		    updateStmt.close();
		} catch (Exception e) {
		    System.out.println(e);
		}
		if(check > 0) {
			System.out.println("成功退出！");
			return true;
		} else {
			System.out.println("退出异常！");
			return false;
		}
	}
	// 注销房间
	public boolean deleteRoom(int roomId) {
		String sql = "DELETE FROM room WHERE room_id = ?";
		int check = 0;
		try {
		    PreparedStatement stmt = conn.prepareStatement(sql);
		    stmt.setInt(1, roomId);
		    check = stmt.executeUpdate();
		    stmt.close();
		} catch (Exception e) {
		    System.out.println(e);
		}
		
	    if (check > 0) {
	        System.out.println("表项删除成功");
	        return true;
	    } else {
	        System.out.println("未找到匹配的表项");
	        return false;
	    }
	}
	
	//根据roomid获取roomaccount
	public int getAccountById(int roomId) {
		int roomaccount = -1;
		String query = "SELECT * FROM room WHERE room_id = '" + roomId + "'";
		try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果
            if (resultSet.next()) {
            	roomaccount = resultSet.getInt("room_account");
            }
            stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
		return roomaccount;
	}
		
	//根据roomaccount获取roomid
	public int getIdByLongAccount(Long roomAccount) {
		int roomId = -1;
		String query = "SELECT * FROM room WHERE room_account = '" + roomAccount + "'";
		try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果
            if (resultSet.next()) {
            	roomId = resultSet.getInt("room_id");
            }
            stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
		return roomId;
	}
	
}